/**
 * Created by hnayan on 2017/8/4.
 */
//使用vuex统一管理状态
const store = new Vuex.Store({
    state: {
        stompClient: null,
        connected: false,
        messages: [],
        routeWhere: 'room'
    },
    mutations: {
        convertStatus(state) {
            state.connected = !state.connected;
        },
        addMessage(state, message) {
            state.messages.unshift(message);
        },
        deleteMessage(state, date) {
            let messages = state.messages;
            for (let i=0;i<messages.length;i++) {
                if (messages[i].date === date) {
                    messages.splice(i, 1);
                    break;
                }
            }
        },
        routeWhere(state, index) {
            state.routeWhere = index;
        }
    },
    actions: {
        convertStatus(context) {
            context.commit('convertStatus');
        }
    }
});
//头部组件数据&函数
const headData = {
    name: 'myHeader',
    template: '#my-header',
    data: function() {
        return {
            content: ''
        };
    },
    methods: {
        sendMessage: function (e) {
            if (!this.$store.state.connected) {
                this.notify({
                    title: 'no connection',
                    message: 'Please connect first.',
                    type: 'error'
                });
                return false;
            }
            this.$store.state.stompClient.send("/app/hello", {}, JSON.stringify({content: this.content}));
        },
        connectWS: function () {
            let socket = new SockJS('/chat-room');
            let stompClient = this.$store.state.stompClient = Stomp.over(socket);
            stompClient.debug = null;
            stompClient.connect({},  () => {
                this.notify({
                    title: 'connect successful',
                    message: 'type some thing.',
                    type: 'success'
                });
                this.$store.dispatch('convertStatus');
                stompClient.subscribe('/topic/reply', function (greeting) {
                    this.$store.commit('addMessage', JSON.parse(greeting.body));
                }.bind(this));
            });
        },
        disconnectWS: function () {
            let stompClient = this.$store.state.stompClient;
            if (stompClient != null) {
                stompClient.disconnect();
                this.notify({
                    title: 'disconnect successful',
                    message: 'now disconnected.',
                    type: 'info'
                });
                this.$store.dispatch('convertStatus');
            } else {
                this.notify({
                    title: 'already disconnect',
                    message: 'make sure button status.',
                    type: 'error'
                });
            }

        },
        notify: function (o) {
            //添加公有属性
            this.$notify(Object.assign(o, {
                duration: 2000,
                offset: 200
            }));
        }
    },
    computed: {
        connected() {
            return this.$store.state.connected;
        }
    }
};
//主体部分
const bodyData = {
    name: 'myBody',
    template: '#my-body',
    data: function () {
        return {
            copy: 'copy!'
        };
    },
    methods: {
        formatDate: function (cellValue) {
            return moment(new Date(cellValue)).format('YYYY-MM-DD HH:mm:ss');
        },
        deleteThat: function (date) {
            this.$store.commit('deleteMessage', date);
        }
    },
    // computed: {
    //     connected() {
    //         return this.$store.state.connected
    //     },
    //     messages() {
    //         return this.$store.state.messages
    //     }
    // },
    //另一种写法
    computed: Vuex.mapState([
        'connected',
        'messages'
    ]),
    components: {
        'my-static': {
            template:
                `
                <el-row type="flex" justify="center" style="margin-top: 5px;">
                        <el-col :span="20">
                            <el-card class="box-card" :body-style="{ padding:'0px',height:'550px' }">
                                <img src="/pic/cat.jpg" class="image" width="100%" height="550" >
                            </el-card>
                        </el-col>
                    </el-row>
                `
        }
    }
};
//底部
const footData = {
    name: 'myFoot',
    template: '#my-foot',
    methods: {
        logout() {
            axios.get('/logout')
                .then(response => {
                    window.location.href = response.data === 'success' ? '/login' : 'index';
                })
                .catch(error => {
                    console.log(error);
                });
        },
        routeWhere(index, indexPath) {
            this.$store.commit('routeWhere', index);
        }
    },
    computed: {
        routeIndex() {
            return this.$store.state.routeWhere;
        }
    }
};
const something = {
    template: `<div>
                   <div style="background-color: antiquewhite;height: 600px;">
                    something
                   </div>
                    <my-foot style="background-color: antiquewhite"></my-foot>
               </div>`,
    name: 'something',
    components: {
        'my-foot': footData
    }
};
const chatroom = {
    name: 'chatRoom',
    template: '#chatroom',
    components: {
        'my-header': headData,
        'my-body': bodyData,
        'my-foot': footData
    }
};
const routes = [
    {
        path:'/something',
        component: something,
        name: 'something~'
    },
    {
        path:'/chatroom',
        component: chatroom,
        name:'chatroom~'
    },
    //重定向到room
    {
        path: '/',
        redirect: '/chatroom'
    }
];
const router = new VueRouter({
    routes
});
const vue = new Vue({
    store,
    router
}).$mount('#app');
//复制到剪贴板
const clip = new Clipboard('.copyButton');
clip.on('success', () => {
    vue.$message({
        message: 'copy successfully:)',
        type: 'success'
    });
});
clip.on('error', () => {
    vue.$message({
        message: 'copy failed:(',
        type:'error'
    });
});